package server.sys;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import models.sys.AdminMenu;
import models.sys.AdminRole;

import java.util.List;

public class AdminServer extends SystemServer {
    /**
     * 根据角色获取其对应的权限树
     *
     * @return
     */
    public static JSONArray getMenuTreeAcrossRole(AdminRole role) {
        JSONArray menutree = new JSONArray();
        List<AdminMenu> menulist;

        List<AdminMenu> role_menus = role.menus;

        System.out.println(role.toJSON());

        //先找出第一级菜单
        menulist = AdminMenu.find("byParent", -1l).fetch();
        for (AdminMenu adminMenu : menulist) {
            menutree.add(menuToJSON(adminMenu,role_menus));
        }

        return menutree;
    }

    private static JSONObject menuToJSON(AdminMenu adminMenu, List<AdminMenu> role_menus) {
        JSONObject menu = adminMenu.toJSON();
        if (AdminMenu.count("byParent", adminMenu.id) > 0) {
            JSONArray menuarr = new JSONArray();
            List<AdminMenu> menuList = AdminMenu.find("byParent", adminMenu.id).fetch();
            for (AdminMenu m : menuList) {
                menuarr.add(menuToJSON(m, role_menus));
            }
            menu.put("children",menuarr);
        }
        menu.put("item-selected",false);
        for (AdminMenu role_menu : role_menus) {
            if (adminMenu.id == role_menu.id)
                menu.put("item-selected",true);
        }
        return menu;
    }
}
